package com.lanyou.cook.web;


import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.lanyou.cook.common.Constants;
import com.lanyou.cook.datadictionary.InterfaceRunResult;
import com.lanyou.cook.entity.domain.InterfaceLastRunResult;

@RestController
@RequestMapping(Constants.BASE_URL_API + "/interfaceLastRunResults")
public class InterfaceLastRunResultController {
	
	@PersistenceContext
	private EntityManager entityManager;
	/**
	 * 判断监控台是否正常运行
	 * @return 拥有失败接口的
	 */
	// 监控台判断是否运行正常
	@RequiresPermissions(value={"governorControl:view"})
	@RequestMapping(value = "/runStatusOfField", produces = "application/json")
	public String runStatusOfField() {
		CriteriaBuilder cb = entityManager.getCriteriaBuilder();
		CriteriaQuery<String> cq = cb.createQuery(String.class).distinct(true);
		Root<InterfaceLastRunResult> root = cq.from(InterfaceLastRunResult.class);
		
		// 构建WHERE部分
		List<Predicate> predicatesList = new ArrayList<>();
		
		
		predicatesList.add(cb.equal(root.get("runResult"), InterfaceRunResult.Faild.ValueCode));
		cq.where(predicatesList.toArray(new Predicate[predicatesList.size()]));
		
		// 构建SELECT部分
		cq.multiselect( root.get("fieldName").alias("fieldName"));
		TypedQuery<String> q = entityManager.createQuery(cq);
		List<String> queryResult = q.getResultList();
		
		JsonArray jsonDatas = new Gson().toJsonTree(queryResult).getAsJsonArray();
		JsonObject jsonResult = new JsonObject();
		jsonResult.add("fieldNamesOfFailed", jsonDatas);
		return jsonResult.toString();
	} 

	
}